using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

namespace datorgrafik_2
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
     //   SpriteBatch spriteBatch;
        
        private Sphere earthSphere;
        private Sphere oceanSphere;
        private Sphere skySphere;

        private Camera camera;
        private BasicEffect basicEffect;
        //private DateTime optionChange;

        //private bool playAnimation = false;


        Matrix world;
        Matrix view;
        Matrix projection;

        Texture2D earth;
        Texture2D ocean;
        Texture2D sky;

        //int terrainWidth;
        //int terrainHeight;
        //private HSL[,] heightData;

        private Vector3 cameraPosition;
        private Vector3 cameraTarget;
        private Vector3 cameraUpVector;


        private Tank tank;


        //struct HSL
        //{
        //    public double h, s, l;
        //}

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);

            graphics.SynchronizeWithVerticalRetrace = true;
            graphics.PreferredBackBufferHeight = 480;
            graphics.PreferredBackBufferWidth = 800;
            graphics.PreferMultiSampling = true;
            graphics.IsFullScreen = false;

            graphics.GraphicsProfile = GraphicsProfile.HiDef;


            Content.RootDirectory = "Content";
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here
            InitializeCamera();

            RasterizerState rs = new RasterizerState();
            rs.CullMode = CullMode.None;
            //      rs.FillMode = FillMode.WireFrame;
            graphics.GraphicsDevice.RasterizerState = rs;

            base.Initialize();
        }

        /// <summary>
        /// Initializes the camera.
        /// </summary>
        private void InitializeCamera()
        {
            float aspectRatio = GraphicsDevice.DisplayMode.AspectRatio;

            Matrix.CreatePerspectiveFieldOfView(
                MathHelper.PiOver4,
                aspectRatio,
                0.1f,
                1000.0f,
                out projection);

            cameraPosition = new Vector3(0f, 0f, 15f);
            cameraTarget = new Vector3(0f, 0f, 0f);
            cameraUpVector = Vector3.Up;

            Matrix.CreateLookAt(
               ref cameraPosition,
               ref cameraTarget,
               ref cameraUpVector,
               out view);
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
                      // TODO: use this.Content to load your game content here
            basicEffect = new BasicEffect(GraphicsDevice);
            basicEffect.TextureEnabled = true;
            basicEffect.LightingEnabled = true;
            basicEffect.DirectionalLight0.DiffuseColor = new Vector3(1f, 1f, 1f);
            basicEffect.DirectionalLight0.Direction = new Vector3(0f, 1f, 1f);
         
            earth = this.Content.Load<Texture2D>("map");
            earthSphere = new Sphere(this, earth, 0);
            earthSphere.Initialize();

            ocean = Content.Load<Texture2D>("ocean1");
            oceanSphere = new Sphere(this, ocean, 0);
            oceanSphere.Initialize();
            // oceanSphere.DecreaseScale(0.05f);
            oceanSphere.ChangeRadius(0.05f);

            sky = new Texture2D(GraphicsDevice, 800, 600);
            sky = Content.Load<Texture2D>("sky");
            skySphere = new Sphere(this, sky, 200f);
            skySphere.Initialize();

            tank = new Tank(GraphicsDevice, Content, earthSphere.GetHeightData());

            camera = new Camera(tank);

            world = Matrix.Identity;
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();

            // TODO: Add your update logic here
            float dT =(float) gameTime.ElapsedGameTime.TotalMilliseconds;
            float cameraChange = dT * 0.01f;
            float oceanChange = dT * 0.00001f;
            if (Keyboard.GetState().IsKeyDown(Keys.Up))
            {
                camera.DecreaseCamera(cameraChange);
            }
            if (Keyboard.GetState().IsKeyDown(Keys.Down))
            {
                camera.IncreaseCamera(cameraChange);
            }
            if (Keyboard.GetState().IsKeyDown(Keys.R))
            {
                oceanSphere.IncreaseScale(oceanChange);
            }
            if (Keyboard.GetState().IsKeyDown(Keys.T))
            {
                oceanSphere.DecreaseScale(oceanChange);
            }




            camera.UpdateCamera(ref view, ref projection);

            projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, GraphicsDevice.Viewport.AspectRatio, 0.1f, 1000.0f);

            oceanSphere.Update(gameTime);
            earthSphere.Update(gameTime);

            tank.Update(gameTime);

            base.Update(gameTime);
        }

        /// <summary>
        /// Updates the camera.
        /// </summary>
        private void updateCamera()
        {
            Matrix.CreateLookAt(
               ref cameraPosition,
               ref cameraTarget,
               ref cameraUpVector,
               out view);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.Black);

            // TODO: Add your drawing code here

            world = Matrix.Identity;
            basicEffect.World = world;
            basicEffect.View = view;
            basicEffect.Projection = projection;
            earthSphere.Draw(basicEffect);
            oceanSphere.Draw(basicEffect);
            skySphere.Draw(basicEffect);

            tank.Draw(ref world, ref view, ref projection, ref basicEffect);


            base.Draw(gameTime);
        }
    }
}
